#!coding:utf-8	相信这句大家都懂的，不解释
import httplib
#导入需要的python模块urllib，用来对数据进行编码
import urllib
import re
import platform
import socket   #socket模块
import commands   #执行系统命令模块
import fcntl
import struct
import os

def get_ip_address(ifname):
	skt = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	pktString = fcntl.ioctl(skt.fileno(), 0x8915, struct.pack('256s', ifname[:15]))
	print(pktString)
	ipString = socket.inet_ntoa(pktString[20:24])
	print(ipString)
	return ipString
	
#直接了当
def getIp():
	conn=httplib.HTTPConnection('printerreprot.sinaapp.com')
	conn.request('GET', '/ip.php?type=get')
	res=conn.getresponse()
	#print( res.read()  )
	#print(res.status)
	#print(res.msg)
	return res.read();
	pass

def is_in_family_lan_socket():
	HOST='192.168.5.200'
	PORT=28888
	s= socket.socket(socket.AF_INET,socket.SOCK_STREAM)   #定义socket类型，网络通信，TCP
	s.connect((HOST,PORT)) 
	pass
	
def is_in_family_lan_ip():
	localip=get_ip_address("wlan2")
	print( localip[0:9] )
	if( localip[0:8]== "192.168.5" ):
		return True;
	else:
		return False;
	
def hostCanRead( path, check_parent=False ):
	'''
	Check if a given path is readable by the current user.

	:param path: The path to check
	:returns: True or False
	'''

	if os.access(path, os.F_OK) and os.access(path, os.R_OK):
		# The path exists and is readable
		return True

	# The path does not exist
	return False
	pass

def hostCanWrite( path, check_parent=False ):
	'''
	Check if a given path is writeable by the current user.

	:param path: The path to check
	:param check_parent: If the path to check does not exist, check for the
		   ability to write to the parent directory instead
	:returns: True or False
	'''

	if os.access(path, os.F_OK) and os.access(path, os.W_OK):
		# The path exists and is writeable
		return True

	if os.access(path, os.F_OK) and not os.access(path, os.W_OK):
		# The path exists and is not writeable
		return False

	# The path does not exists or is not writeable

	if check_parent is False:
		# We're not allowed to check the parent directory of the provided path
		return False

	# Lets get the parent directory of the provided path
	parent_dir = os.path.dirname(path)

	if not os.access(parent_dir, os.F_OK):
		# Parent directory does not exit
		return False

	# Finally, return if we're allowed to write in the parent directory of the
	# provided path
	return os.access(parent_dir, os.W_OK)
	pass
	
def getHostPath():
	if( platform.system()=='Linux' ):
		return "/etc/hosts"
	else:
		return "C:/Windows/System32/drivers/etc/hosts"
	pass
	
def writeHost( host ):
	f = open( getHostPath(), 'w' )
	f.write( host );
	f.close()
	pass
	
def readHost():
	f = open( getHostPath() )
	contents = f.read()
	f.close()
	return contents
	pass
	
def replaceIt():
	pass

def normal():
	#将所有spsp转换为SPSP
	pass

def findSpspLine():
	host = readHost();
	#spsp_line_regx = r"\n([1-9]|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])(\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])){3}\s+([Ss][Pp][Ss][Pp])";
	#spsp_line_regx = r"\n([1-9]|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])(\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])){3}\s+(spsp)";
	spsp_line_regx = r'\n(?<![\.\d])(?:\d{1,3}\.){3}\d{1,3}(?![\.\d])\s+SPSP';
	mat = re.search( spsp_line_regx, host, re.I )
	print( mat.span()[0] )
	print( host[mat.span()[0]:mat.span()[1]] );
	return mat;
	pass
	
def _updateHost( ip ):
	host = readHost();
	spsp_line_regx = r"\n([1-9]|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])(\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])){3}\s*\S*";
	#spsp_line_regx = r"\\n([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}\\s*\\S*";
	ipreg = r'(?<![\.\d])(?:\d{1,3}\.){3}\d{1,3}(?![\.\d])\s*SPSP'
	#ipreg = r'(?<![\.\d])(?:\d{1,3}\.){3}\d{1,3}(?![\.\d])'
	reip = re.compile( ipreg )	## 将正则表达式编译成Pattern对象
	#reip = re.compile( spsp_line_regx );
	#for ip in reip.findall( host ):
		#print "ip>>>", ip
	mat = re.search( ipreg, host )
	#mat = re.match( ipreg, host, re.I|re.L|re.U )
	print( mat.span() )
	pattern = ipreg
	out = re.sub( pattern, response + " SPSP", host )	#
	#如果没有找到，添加一行
	#print out
	writeHost( out )
	pass

def updateHost( ip ):
	host = readHost();
	if( findSpspLine()!=None ):
		print( "update!, ip: " + ip );
		spsp_line_regx = r'\n(?<![\.\d])(?:\d{1,3}\.){3}\d{1,3}(?![\.\d])\s+SPSP';
		#spsp_line_regx = r'\n(?<![\.\d])(?:\d{1,3}\.){3}\d{1,3}(?![\.\d])\s+SPSP';
		out = re.sub( spsp_line_regx, "\n"+ ip + " SPSP", host, 0, re.I )	#
	else:
		print( "add" );
		out = out + "\n"+ ip + " SPSP"
	writeHost( out )
	pass

def createDoneTag():
	#/tmp/spspUpdated
	f = open( "/tmp/spspUpdated", 'w' )
	f.close()
	pass
	
def action():
	#findSpspLine();
	#return;
	if( False==hostCanRead( getHostPath() ) or False==hostCanWrite( getHostPath() ) ):
		print( "host文件无法读取或者无法写入，无法进行操作" );
		return;
	if( is_in_family_lan_ip() ):
		updateHost( "192.168.5.200" );
	else:
		response = getIp();
		#chech the response is ip
		ipreg = r'(?<![\.\d])(?:\d{1,3}\.){3}\d{1,3}(?![\.\d])'
		updateHost( response );
	createDoneTag();

def setup():
	#安装到/etc/network/if-up.d
	
	pass
	
if __name__ == "__main__":
	action();
